//od简单.给定额度购买三个商品的最大消费金额
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
#define PF(...) printf(__VA_ARGS__)
int getMaxCost(const vector<int>& vtPrice, int nMoney) {
  int  nMax = -1;
  for (size_t i = 0; i < vtPrice.size(); i++){
    for (size_t j = i + 1; j < vtPrice.size(); j++) {
      for (size_t k = j + 1; k < vtPrice.size(); k++) {
        int nCost = vtPrice[i] + vtPrice[j] + vtPrice[k];
        if (nCost <= nMoney) {
          nMax = std::max(nMax, nCost);
        }

      }
    }
  }
  return nMax;
}

int main_2() {
  string strIn;
  getline(cin, strIn);
  {
    int nMoney = 0;
    cin >> nMoney;
    // to array
    stringstream iss(strIn);
    string sNum;
    vector<int> vtPrice;
    while (getline(iss, sNum, ',') ) {
      vtPrice.push_back(atoi(sNum.c_str()));
    }
    // test print
    //for (auto np : vtPrice) PF("%d,", np); PF("\n");
    //
    int nOut = getMaxCost(vtPrice, nMoney);
    printf("%d\n", nOut);
  }
  return 0;
}
